//
//  ScaleData.m
//  HealthScale
//
//  Created by zhangjikun on 12-11-7.
//  Copyright (c) 2012年 无比动力. All rights reserved.
//

#import "ScaleData.h"

@implementation ScaleData
+(NSMutableArray *)loadScaleData:(NSString *)fileName
{
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [path objectAtIndex:0];
    NSString *strPath = [documentDirectory stringByAppendingPathComponent:fileName];
    if ([[NSFileManager defaultManager] fileExistsAtPath:strPath])

    {        
        NSMutableArray *array=[[NSMutableArray alloc]initWithContentsOfFile:strPath];
        return array;
    }
    return nil;
}

+(BOOL)SaveScaleData:(id)scaleInfo FileName:(NSString *)fileName
{
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [path objectAtIndex:0];
    NSString *strPath = [documentDirectory stringByAppendingPathComponent:fileName];
    if(strPath != nil)//转成NSData数据存入
    {
        NSMutableArray *array =[ScaleData loadScaleData:fileName];
        if (array==nil) {
            array=[[NSMutableArray alloc]initWithCapacity:100];
        }
        NSData *data =[NSKeyedArchiver archivedDataWithRootObject:scaleInfo];
        [array addObject:data];
        [array writeToFile:strPath atomically:YES];
        return YES;
    }    
    return NO;
}
+(BOOL)DeleteScaleInfo:(id)scaleInfo FileName:(NSString *)fileName
{
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [path objectAtIndex:0];
    NSString *strPath = [documentDirectory stringByAppendingPathComponent:fileName];
    if(strPath != nil)//转成NSData数据存入
    {
        NSMutableArray *array =[ScaleData loadScaleData:fileName];
        if ( [array count] ) {
        NSData *data =[NSKeyedArchiver archivedDataWithRootObject:scaleInfo];
        [array removeObject:data];
        [array writeToFile:strPath atomically:YES];
        return YES;
        }
        return NO;
    }    
    return NO;
}

+(void)DeleteScaleData:(NSString *)fileName
{
    //创建文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //获取路径
    //参数NSDocumentDirectory要获取那种路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    
    //更改到待操作的目录下
    [fileManager changeCurrentDirectoryPath:[documentsDirectory stringByExpandingTildeInPath]];
    
//    //创建文件fileName文件名称，contents文件的内容，如果开始没有内容可以设置为nil，attributes文件的属性，初始为nil
//    [fileManager createFileAtPath:@"fileName" contents:nil attributes:nil];
    
    //删除待删除的文件
    [fileManager removeItemAtPath:fileName error:nil];
}
@end
